/**
 * @author zjkermit
 * @email zjkermit@gmail.com
 * @date Mar 13, 2014
 */
package zhoujian.oj.leetcode;

import org.junit.Test;

/**
 * @version 1.0
 * @description Given an integer n, generate a square matrix filled with
 *              elements from 1 to n2 in spiral order.
 * 
 *              For example, Given n = 3,
 * 
 *              You should return the following matrix: 
 *              [ 
 *              	[ 1, 2, 3 ], 
 *              	[ 8, 9, 4 ], 
 *              	[ 7, 6, 5 ] 
 *              ]
 */
public class SpiralMatrixII {

	public int[][] generateMatrix(int n) {
		if (n < 1)
			return new int[][] {};
		int[][] res = new int[n][n];
		int direct = 1;
		int i = 0;
		int j = 0;
		res[i][j] = 1;
		for (int k = 2; k <= n * n; k++) {
			switch (direct) {
				// '1' means to right
				case 1 : {
					if (check(res, i, j + 1)) {
						res[i][++j] = k;
					} else {
						direct = 2;
						k--;
					}
				} break;
				// '2' means to bottom
				case 2 : {
					if (check(res, i + 1, j)) {
						res[++i][j] = k;
					} else {
						direct = 3;
						k--;
					}
				} break;
				// '3' means to left
				case 3 : {
					if (check(res, i - 1, j)) {
						res[--i][j] = k;
					} else {
						direct = 4;
						k--;
					}
				} break;
				// '4' means to top
				case 4 : {
					if (check(res, i, j - 1)) {
						res[i][--j] = k;
					} else {
						direct = 1;
						k--;
					}
				} break;
			}
		}
		return res;
    }
	
	private boolean check(int[][] matrix, int i, int j) {
		if (i < 0 || i > matrix.length -1 || j < 0 || j > matrix.length - 1)
			return false;
		else 
			return matrix[i][j] == 0;
	}
	
	@Test
	public void test() {
		int[][] res = generateMatrix(5);
		for (int[] row : res) {
			for (int col : row) {
				System.out.print(col + " ");
			}
			System.out.println();
		}
	}
}
